package com.zklh.leetcode.array.middle.problem16;

import java.util.Arrays;

/**
 * @author 坐看落花
 * @version 1.0
 * @date 2023/5/6 15:19
 */
public class Solution {

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        // 定义三个指针
        int current, left, right;
        int threeSumClosest = Integer.MAX_VALUE;
        int tempThreeSum = Integer.MAX_VALUE;
        for (current = 1; current < nums.length - 1; current++) {
            left = current - 1;
            right = current + 1;
            int min = nums[0] + nums[current] + nums[right];
            int max = nums[left] + nums[nums.length-1] + nums[current];
            if (min > target && Math.abs(tempThreeSum - target) < Math.abs(threeSumClosest - target)) {
                if (Math.abs(min - target) < Math.abs(threeSumClosest - target)) {
                    threeSumClosest = min;
                }
                continue;
            }
            if (max < target) {
                if (Math.abs(max - target) < Math.abs(threeSumClosest - target)) {
                    threeSumClosest = max;
                }
                continue;
            }
            while (left >= 0 && right < nums.length) {
                tempThreeSum = nums[left] + nums[current] + nums[right];
                if (Math.abs(tempThreeSum - target) < Math.abs(threeSumClosest - target)) {
                    threeSumClosest = tempThreeSum;
                }
                if (tempThreeSum > target) {
                    while (--left >= 0 && nums[left] == nums[left + 1]);
                } else if (tempThreeSum < target) {
                    while (++right < nums.length && nums[right] == nums[right-1]);
                } else {
                    return tempThreeSum;
                }
            }
        }
        return threeSumClosest;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.threeSumClosest(new int[]{0,3,97,102,200}, 300));
    }
}
